//+------------------------------------------------------------------+
//| 五浪理论遗传算法日志管理模块
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

// 日志级别枚举
enum LOG_LEVEL {
    LOG_DEBUG = 0,    // 调试信息
    LOG_INFO = 1,     // 一般信息
    LOG_WARNING = 2,  // 警告信息
    LOG_ERROR = 3,    // 错误信息
    LOG_TRADE = 4     // 交易信息
};

// 日志配置结构
struct LogConfig {
    bool enableDebugLog;      // 启用调试日志
    bool enableTradeLog;      // 启用交易日志
    bool enableWaveLog;       // 启用波浪识别日志
    bool enableGALog;         // 启用遗传算法日志
    bool enablePerformanceLog; // 启用性能日志
    string logFilePath;       // 日志文件路径
    int maxLogFileSize;       // 最大日志文件大小(KB)
};

// 全局日志配置
LogConfig g_logConfig;

//+------------------------------------------------------------------+
//| 初始化日志系统
//+------------------------------------------------------------------+
void InitWaveTheoryLogger(bool enableDebug = true, bool enableTrade = true, 
                         bool enableWave = true, bool enableGA = true, 
                         bool enablePerformance = true) {
    g_logConfig.enableDebugLog = enableDebug;
    g_logConfig.enableTradeLog = enableTrade;
    g_logConfig.enableWaveLog = enableWave;
    g_logConfig.enableGALog = enableGA;
    g_logConfig.enablePerformanceLog = enablePerformance;
    g_logConfig.logFilePath = "Logs\\WaveTheory_GA_" + Symbol() + "_" + 
                             IntegerToString(TimeCurrent()) + ".log";
    g_logConfig.maxLogFileSize = 10240; // 10MB
    
    // 创建日志目录
    string logDir = "Logs";
    if(!FolderCreate(logDir)) {
        if(GetLastError() != ERR_DIRECTORY_EXISTS) {
            Print("警告: 无法创建日志目录 ", logDir);
        }
    }
    
    LogMessage(LOG_INFO, "=== 五浪理论遗传算法系统启动 ===");
    LogMessage(LOG_INFO, "交易品种: " + Symbol());
    LogMessage(LOG_INFO, "时间框架: " + EnumToString(Period()));
    LogMessage(LOG_INFO, "日志文件: " + g_logConfig.logFilePath);
}

//+------------------------------------------------------------------+
//| 记录日志消息
//+------------------------------------------------------------------+
void LogMessage(LOG_LEVEL level, string message, bool printToConsole = true) {
    string levelStr = "";
    switch(level) {
        case LOG_DEBUG: levelStr = "[DEBUG]"; break;
        case LOG_INFO: levelStr = "[INFO]"; break;
        case LOG_WARNING: levelStr = "[WARNING]"; break;
        case LOG_ERROR: levelStr = "[ERROR]"; break;
        case LOG_TRADE: levelStr = "[TRADE]"; break;
    }
    
    string timestamp = TimeToString(TimeCurrent(), TIME_DATE | TIME_SECONDS);
    string logMessage = timestamp + " " + levelStr + " " + message;
    
    // 输出到控制台
    if(printToConsole) {
        Print(logMessage);
    }
    
    // 写入日志文件
    int fileHandle = FileOpen(g_logConfig.logFilePath, FILE_WRITE | FILE_TXT | FILE_ANSI);
    if(fileHandle != INVALID_HANDLE) {
        FileSeek(fileHandle, 0, SEEK_END);
        FileWriteString(fileHandle, logMessage + "\n");
        FileClose(fileHandle);
    }
}

//+------------------------------------------------------------------+
//| 记录波浪识别日志
//+------------------------------------------------------------------+
void LogWaveIdentification(int barIndex, string waveType, double high, double low, 
                          double close, double amplitude, double retracement, 
                          bool isValid, string reason = "") {
    if(!g_logConfig.enableWaveLog) return;
    
    string message = StringFormat("波浪识别 - 位置:%d 类型:%s 最高:%.5f 最低:%.5f 收盘:%.5f 幅度:%.5f 回撤:%.3f 有效:%s %s",
                                 barIndex, waveType, high, low, close, amplitude, retracement, 
                                 isValid ? "是" : "否", reason);
    LogMessage(LOG_INFO, message);
}

//+------------------------------------------------------------------+
//| 记录支撑阻力位日志
//+------------------------------------------------------------------+
void LogSupportResistance(double price, string type, int touchCount, double strength, 
                         bool isActive, string reason = "") {
    if(!g_logConfig.enableWaveLog) return;
    
    string message = StringFormat("支撑阻力位 - 价格:%.5f 类型:%s 触及次数:%d 强度:%.3f 活跃:%s %s",
                                 price, type, touchCount, strength, isActive ? "是" : "否", reason);
    LogMessage(LOG_INFO, message);
}

//+------------------------------------------------------------------+
//| 记录遗传算法日志
//+------------------------------------------------------------------+
void LogGeneticAlgorithm(int generation, int individualIndex, double fitness, 
                        double winRate, double profitFactor, double maxDrawdown, 
                        double sharpeRatio, string operation = "") {
    if(!g_logConfig.enableGALog) return;
    
    string message = StringFormat("遗传算法 - 代数:%d 个体:%d 适应度:%.4f 胜率:%.1f%% 盈亏比:%.2f 回撤:%.1f%% 夏普:%.2f %s",
                                 generation, individualIndex, fitness, winRate * 100, 
                                 profitFactor, maxDrawdown * 100, sharpeRatio, operation);
    LogMessage(LOG_INFO, message);
}

//+------------------------------------------------------------------+
//| 记录交易信号日志
//+------------------------------------------------------------------+
void LogTradeSignal(bool isBuy, double price, double stopLoss, double takeProfit, 
                   string signalType, double confidence, string reason = "") {
    if(!g_logConfig.enableTradeLog) return;
    
    string direction = isBuy ? "买入" : "卖出";
    string message = StringFormat("交易信号 - 方向:%s 价格:%.5f 止损:%.5f 止盈:%.5f 信号类型:%s 置信度:%.2f %s",
                                 direction, price, stopLoss, takeProfit, signalType, confidence, reason);
    LogMessage(LOG_TRADE, message);
}

//+------------------------------------------------------------------+
//| 记录交易执行日志
//+------------------------------------------------------------------+
void LogTradeExecution(ulong ticket, bool isBuy, double openPrice, double volume, 
                      double stopLoss, double takeProfit, string comment = "") {
    if(!g_logConfig.enableTradeLog) return;
    
    string direction = isBuy ? "买入" : "卖出";
    string message = StringFormat("交易执行 - 订单号:%d 方向:%s 开仓价:%.5f 手数:%.2f 止损:%.5f 止盈:%.5f %s",
                                 ticket, direction, openPrice, volume, stopLoss, takeProfit, comment);
    LogMessage(LOG_TRADE, message);
}

//+------------------------------------------------------------------+
//| 记录交易结果日志
//+------------------------------------------------------------------+
void LogTradeResult(ulong ticket, bool isWin, double profit, double openPrice, 
                   double closePrice, datetime openTime, datetime closeTime, 
                   string closeReason = "") {
    if(!g_logConfig.enableTradeLog) return;
    
    string result = isWin ? "盈利" : "亏损";
    double duration = (double)(closeTime - openTime) / 3600.0; // 小时
    
    string message = StringFormat("交易结果 - 订单号:%d 结果:%s 盈亏:%.2f 开仓价:%.5f 平仓价:%.5f 持仓时间:%.1f小时 %s",
                                 ticket, result, profit, openPrice, closePrice, duration, closeReason);
    LogMessage(LOG_TRADE, message);
}

//+------------------------------------------------------------------+
//| 记录性能统计日志
//+------------------------------------------------------------------+
void LogPerformanceStats(int totalTrades, int winTrades, double totalProfit, 
                        double totalLoss, double winRate, double profitFactor, 
                        double maxDrawdown, double sharpeRatio, int period = 0) {
    if(!g_logConfig.enablePerformanceLog) return;
    
    string periodStr = (period > 0) ? StringFormat("(周期:%d)", period) : "";
    string message = StringFormat("性能统计%s - 总交易:%d 盈利:%d 总盈利:%.2f 总亏损:%.2f 胜率:%.1f%% 盈亏比:%.2f 回撤:%.1f%% 夏普:%.2f",
                                 periodStr, totalTrades, winTrades, totalProfit, totalLoss, 
                                 winRate * 100, profitFactor, maxDrawdown * 100, sharpeRatio);
    LogMessage(LOG_INFO, message);
}

//+------------------------------------------------------------------+
//| 记录参数优化日志
//+------------------------------------------------------------------+
void LogParameterOptimization(string parameterName, double oldValue, double newValue, 
                             double improvement, string reason = "") {
    if(!g_logConfig.enableGALog) return;
    
    string message = StringFormat("参数优化 - 参数:%s 原值:%.5f 新值:%.5f 改进:%.3f %s",
                                 parameterName, oldValue, newValue, improvement, reason);
    LogMessage(LOG_INFO, message);
}

//+------------------------------------------------------------------+
//| 记录市场状态日志
//+------------------------------------------------------------------+
void LogMarketState(string state, double volatility, double trend, double volume, 
                   string description = "") {
    if(!g_logConfig.enableDebugLog) return;
    
    string message = StringFormat("市场状态 - 状态:%s 波动率:%.3f 趋势:%.3f 成交量:%.0f %s",
                                 state, volatility, trend, volume, description);
    LogMessage(LOG_INFO, message);
}

//+------------------------------------------------------------------+
//| 记录错误日志
//+------------------------------------------------------------------+
void LogError(string function, string error, int errorCode = 0) {
    string message = StringFormat("错误 - 函数:%s 错误:%s 代码:%d", function, error, errorCode);
    LogMessage(LOG_ERROR, message);
}

//+------------------------------------------------------------------+
//| 记录警告日志
//+------------------------------------------------------------------+
void LogWarning(string function, string warning, string suggestion = "") {
    string message = StringFormat("警告 - 函数:%s 警告:%s %s", function, warning, suggestion);
    LogMessage(LOG_WARNING, message);
}

//+------------------------------------------------------------------+
//| 记录系统状态日志
//+------------------------------------------------------------------+
void LogSystemStatus(string status, double memoryUsage, int activeOrders, 
                    int pendingOrders, string details = "") {
    string message = StringFormat("系统状态 - 状态:%s 内存:%.1fMB 活动订单:%d 挂单:%d %s",
                                 status, memoryUsage, activeOrders, pendingOrders, details);
    LogMessage(LOG_INFO, message);
}

//+------------------------------------------------------------------+
//| 生成详细报告
//+------------------------------------------------------------------+
void GenerateDetailedReport() {
    string report = "\n=== 五浪理论遗传算法详细报告 ===\n";
    report += "生成时间: " + TimeToString(TimeCurrent(), TIME_DATE | TIME_SECONDS) + "\n";
    report += "交易品种: " + Symbol() + "\n";
    report += "时间框架: " + EnumToString(Period()) + "\n";
    report += "当前价格: " + DoubleToString(SymbolInfoDouble(Symbol(), SYMBOL_BID), _Digits) + "\n";
    report += "账户余额: " + DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE), 2) + "\n";
    report += "账户权益: " + DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY), 2) + "\n";
    report += "浮动盈亏: " + DoubleToString(AccountInfoDouble(ACCOUNT_PROFIT), 2) + "\n";
    
    LogMessage(LOG_INFO, report);
}

//+------------------------------------------------------------------+
//| 清理旧日志文件
//+------------------------------------------------------------------+
void CleanupOldLogs(int maxAgeDays = 7) {
    string logDir = "Logs";
    string fileName;
    long fileHandle = FileFindFirst(logDir + "\\*.log", fileName);
    
    if(fileHandle != INVALID_HANDLE) {
        do {
            string fullPath = logDir + "\\" + fileName;
            long fileTime = FileGetInteger(fullPath, FILE_MODIFY_DATE);
            long currentTime = TimeCurrent();
            
            if((currentTime - fileTime) > (maxAgeDays * 24 * 3600)) {
                FileDelete(fullPath);
                LogMessage(LOG_INFO, "删除旧日志文件: " + fileName);
            }
        } while(FileFindNext(fileHandle, fileName));
        FileFindClose(fileHandle);
    }
} 